package conf

import (
	"DataServer/common/logger"
	"encoding/xml"
	"io/ioutil"
	"strings"
)

type MysqlConf struct {
	Ip           string `xml:",attr"`
	Port         int    `xml:",attr"`
	User         string `xml:",attr"`
	Pwd          string `xml:",attr"`
	Database     string `xml:",attr"`
	LoadInterval int    `xml:",attr"`
}

type ServerHttpAddrConf struct {
	Host string `xml:",attr"`
}

type ClientHttpAddrConf struct {
	Host     string `xml:",attr"`
	WhiteUID string `xml:",attr"`
}

type RPCListenAddrConf struct {
	Host string `xml:",attr"`
}
type MongoAddrConf struct {
	Host     string `xml:",attr"`
	DB       string `xml:",attr"`
	Keepdays int    `xml:",attr"`
}
type MQ struct {
	Uri          string `xml:",attr"`
	Exchange     string `xml:",attr"`
	ExchangeType string `xml:",attr"`
	Queue        string `xml:",attr"`
	BindingKey   string `xml:",attr"`
	ConsumerTag  string `xml:",attr"`
	LifeTime     int    `xml:",attr"`
}

type TexasConf struct {
	GameDBMysql    MysqlConf          `xml:"GameDB"`
	PlayerMysql    MysqlConf          `xml:"PlayerMysql"`
	HistoryMysql   MysqlConf          `xml:"HistoryMysql"`
	ServerHttpAddr ServerHttpAddrConf `xml:"ServerHttpAddr"`
	ClientHttpAddr ClientHttpAddrConf `xml:"ClientHttpAddr"`
	RPCListenAddr  RPCListenAddrConf  `xml:"RPCListenAddr"`
	MongoAddr      MongoAddrConf      `xml:"MongoAddr"`
	MQConf         MQ                 `xml:"MQ"`
}

var (
	config = new(TexasConf)
)

func GetGameDBConf() MysqlConf {
	return config.GameDBMysql
}
func GetMQConf() MQ {
	return config.MQConf
}
func GetPlayerMysqlConf() MysqlConf {
	return config.PlayerMysql
}

func GetHistoryMysqlConf() MysqlConf {
	return config.HistoryMysql
}
func GetServerHttpAddrConf() string {
	return config.ServerHttpAddr.Host
}
func GetClientHttpAddrConf() string {
	return config.ClientHttpAddr.Host
}

func GetWhiteUID() []string {
	whiteUids := strings.Split(config.ClientHttpAddr.WhiteUID, ",")
	logger.Info("conf WhiteUID: %v", whiteUids, ",")
	return whiteUids
}

func GetRPCListenAddrConf() string {
	return config.RPCListenAddr.Host
}
func GetMongoAddrConf() string {
	return config.MongoAddr.Host
}
func GetMongoDBName() string {
	return config.MongoAddr.DB
}
func GetPaipuKeepdays() int {
	if config.MongoAddr.Keepdays == 0 {
		return 15
	}
	return config.MongoAddr.Keepdays
}

func LoadConf(filename string) error {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		logger.Info("read file:%v error:%v", filename, err)
		return err
	}
	logger.Info("conf xml:%v", string(content))
	err = xml.Unmarshal(content, config)
	if err != nil {
		logger.Info("decode xml error:%v", err)
		return err
	}

	DumpConf()
	return nil
}

func DumpConf() {
	logger.Info("Player Mysql :%+v", config.PlayerMysql)
	logger.Info("History Mysql :%+v", config.HistoryMysql)
	logger.Info("all config:%+v", config)
}
